package com.diyizu.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.entity.SysUser;
import com.diyizu.youdianda.entity.YddUser;
import com.diyizu.youdianda.service.YddUserService;
import com.diyizu.youdianda.util.JwtUtils;
import com.diyizu.youdianda.util.UserID;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/home/index")
public class HomeController {

    @Autowired
    private YddUserService yddUserService;

    @PostMapping("/login")
    public R login(@RequestBody YddUser yddUser){
        String mobile = yddUser.getMobile();
        String pwd = yddUser.getPassword();
        String password = DigestUtils.md5DigestAsHex(pwd.getBytes());
        long id = yddUser.getId();
        UserID.setCurrentId(Long.toString(id));

        LambdaQueryWrapper<YddUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddUser::getMobile, mobile);
        YddUser user = yddUserService.getOne(lqw);
        if (user == null){
//            yddUserService.save(yddUser);
//
//            HashMap hashMap = new HashMap<>();
//            hashMap.put("id",yddUser.getId());
//            String token = JwtUtils.getToken(hashMap);
//
//            HashMap<String, String> map = new HashMap<>();
//            map.put("token",token);
//
//            return R.success(map);
            return R.error("账号不存在,请先注册");
        }
        if (password.equals(user.getPassword())){

            HashMap hashMap = new HashMap<>();
            hashMap.put("id",user.getId());
            String token = JwtUtils.getToken(hashMap);

            HashMap<String, String> map = new HashMap<>();
            map.put("token",token);

            return R.success(map);
        }

        return R.error("密码错误");
    }
}
